import json

from peewee import *
import scrapy

from .models import BaseModel

from .celery import app
from celery.utils.log import get_task_logger
logger = get_task_logger(__name__)

import logging

logger = logging.getLogger('peewee')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)

class Category(BaseModel):
    id = AutoField(primary_key=True)
    name = CharField(max_length=512)    
    obj_id = IntegerField()
    site = CharField(max_length=32)
    class Meta:
        table_name = 'app_category'
class Author(BaseModel):
    id = AutoField(primary_key=True)
    name = CharField(max_length=512)    
    obj_id = IntegerField()
    site = CharField(max_length=32)
    class Meta:
        table_name = 'app_author'
class Apk(BaseModel):
    id = AutoField(primary_key=True)
    name = CharField(max_length=512)
    new_feature = TextField()
    pkg_name = CharField(max_length=128)
    version_code = IntegerField()
    version_name = CharField(max_length=32)
    images = CharField(max_length=10240)
    publish_at = DateTimeField()
    icon_url = CharField(max_length=10240)
    download_cnt = BigIntegerField()
    file_size = IntegerField()
    category = ForeignKeyField(Category)
    author = ForeignKeyField(Author)
    

    obj_id = IntegerField()
    site = CharField(max_length=32)    

    class Meta:
        table_name = 'app_apk'



class AppItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    site = scrapy.Field()
    id = scrapy.Field()
    name = scrapy.Field()
    file_size = scrapy.Field()
    download_cnt = scrapy.Field()
    icon_url = scrapy.Field()
    new_feature = scrapy.Field()
    pkg_name = scrapy.Field()
    version_code = scrapy.Field()
    version_name = scrapy.Field()
    images = scrapy.Field()
    publish_at = scrapy.Field()
    author = scrapy.Field()
    category = scrapy.Field()    



class AppPipeline(object):
    def process_item(self, item, spider):
        if isinstance(item, AppItem):
            pass
        return item


def save_category(item):
    category = item.get('category')
    cat = Category.get_or_none(Category.obj_id == category.get('id'), Category.site == item.get('site'))
    if not cat:
        category['site'] = item.get('site')
        category['obj_id'] = category.get('id')
        del category['id']
        print(category)
        cat = Category.create(**category)
    return cat

def save_author(item):
    obj = item.get('author')
    author = Author.get_or_none(Author.obj_id == obj.get('id'), Author.site == item.get('site'))
    if not author:
        obj['site'] = item.get('site')
        obj['obj_id'] = obj.get('id')
        del obj['id']
        author = Author.create(**obj)
    return author

@app.task
def save_apk(item):
    logger.info('save apk %s', item.get('name'))
    cat = save_category(item)
    author = save_author(item)
    apk = Apk.get_or_none(Apk.obj_id== item.get('id'),Apk.site == item.get('site'))
    if apk:
        pass
    else:
        kk = dict(item)
        kk['obj_id'] = kk['id']
        del kk['id']
        if kk['images']:
            kk['images'] = json.dumps(kk['images'])
        kk['author'] = author
        kk['category'] = cat
        Apk.create(**kk)
    # novel = Book.get_or_none(Book.slug == item.get('slug'))
    # if novel:
    #     novel.__data__.update(dict(item))
    #     novel.save()
    # else:
    #     Book.create(**dict(item))